package com.home.qh.webapp.controller;

import java.beans.PropertyEditorSupport;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.City;
import com.home.qh.model.Country;
import com.home.qh.model.Vessel;
import com.home.qh.service.CountryManager;
import com.home.qh.service.VesselManager;

@Controller
@RequestMapping("/admin/vesselForm.*")
public class VesselFormController extends BaseFormController{
	private transient final Log log = LogFactory.getLog(VesselFormController.class);
	 private MessageSource messageSource = null;
	private VesselManager mgr;
	private CountryManager countryManager;
    
    @Autowired
    private ApplicationContext context;

    @Autowired
    public void setVesselManager(VesselManager vesselManager) {
        this.mgr = vesselManager;
    }	
        
    @Autowired
	public void setCountryManager(CountryManager countryManager){
		this.countryManager = countryManager;
	}
    
    public VesselFormController() {
        setCancelView("redirect:/admin/vesselList.html");
        setSuccessView("redirect:/admin/vesselList.html");
    }
    
    @Override
	public String getText(String msgKey, Object[] args, Locale locale) {
		// TODO Auto-generated method stub
		return super.getText(msgKey, args, locale);
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) {
//		super.initBinder(request, binder);
		binder.registerCustomEditor(Country.class, "country", 
                new PropertyEditorSupport() {
        	public void setAsText(String id)
        	{
        		long longId = Long.parseLong(id);
        		if (longId > 0)
        		{
        			Country country = countryManager.get(longId);
        			setValue(country);
        		}
        	}
        });
	}
    
    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ModelAndView view = new ModelAndView("admin/vesselForm");
        view.addObject("countryList", countryManager.getAll());
        log.debug("entering 'showForm' method...");
        if (!isFormSubmission(request)) {
            String vesselId = request.getParameter("id"); 
            Vessel vessel = null;
	        if (vesselId == null || isAdd(request)) {
	        	vessel = new Vessel();
	        } else if (!StringUtils.isBlank(vesselId)) {
	        	vessel = mgr.get(Long.parseLong(vesselId));
	        }
	        view.addObject("vessel", vessel);
        }
    	return view;
    }
    
    /* (non-Javadoc)
	 * @see com.home.qh.webapp.controller.BaseFormController#saveError(javax.servlet.http.HttpServletRequest, java.lang.String)
	 */
	@Override
	public void saveError(HttpServletRequest request, String error) {
		// TODO Auto-generated method stub
		System.out.println("coming save error!");
		super.saveError(request, error);
	}
	
	
	
	@RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(Vessel vessel, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            if (!StringUtils.equals(request.getParameter("from"), "list")) {
                return new ModelAndView(getCancelView());
            } else {
                return new ModelAndView(getSuccessView()) ;
            }
        }
        
        Locale locale = request.getLocale();
        MessageSourceAccessor text = new MessageSourceAccessor(messageSource, locale);
        if (vessel.getName()==null || vessel.getName().equals("")){
        	errors.rejectValue("name", "Error.NAME_REQUIRED", "Name is required!");
        }
        
        if(vessel.getCode()==null || vessel.getCode().equals("")){
        	errors.rejectValue("code", "Error.CODE_REQUIRED", "Code is required!");
        }
        
        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return showForm(request, response);
        }
        
        if (request.getParameter("delete") != null) {
        	mgr.remove(vessel.getId());
            return new ModelAndView(getSuccessView()) ;
        } else {
        	if (vessel == null)
        		vessel = new Vessel();   
        	log.debug("Save vessel succesfully");
        	
        	mgr.save(vessel);
            return new ModelAndView(getSuccessView()) ;   	
        }
    }

    private boolean isFormSubmission(HttpServletRequest request) {
        return request.getMethod().equalsIgnoreCase("post");
    }

    protected boolean isAdd(HttpServletRequest request) {
        String method = request.getParameter("method");
        return (method != null && method.equalsIgnoreCase("add"));
    }  
}